<template>
  <div class="contact-json">
    <!-- 联系方式 -->
    <div class="contact-json-row" v-for="(item, index) in value" :key="index">
      <ElSelect
        class="contact-json-type"
        placeholder=""
        :model-value="item.type"
        @update:model-value="onChangeType($event, index)"
      >
        <ElOption v-for="op in typeList" :key="op.value" :value="op.value" :label="op.label"/>
      </ElSelect>
      <ElInput
        class="contact-json-no"
        :model-value="item.no"
        @update:model-value="onChangeNo($event, index)"
      />
      <ElButton
        v-if="!index"
        link
        type="primary"
        @click="onAdd"
      >添加</ElButton>
      <ElButton
        v-if="index"
        link
        type="primary"
        @click="onRemove(index)"
      >删除</ElButton>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElButton, ElInput, ElSelect, ElOption } from 'element-plus';

const typeList = [
  { value: '电话', label:'电话' },
  { value: '微信', label:'微信' },
  { value: 'QQ', label: 'QQ' },
  { value: '千牛', label: '千牛' },
  { value: '抖音', label: '抖音' },
  { value: '拼多多', label: '拼多多' },
  { value: '百度', label: '百度' },
  { value: '其他', label: '其他' },
]
import { computed } from 'vue'
interface Props {
  modelValue: string;
  data: object;
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  data: () => ({})
})

interface Emits {
  'update:model-value': [string]
}
const emit = defineEmits<Readonly<Emits>>()

const value = computed(() => {
  if (!props.modelValue) return [{ type: '', no: '' }]
  return JSON.parse(props.modelValue)
})

const onAdd = () => {
  const val = [...value.value]
  val.push({ type: '', no: '' })
  emit('update:model-value', JSON.stringify(val))
}

const onChangeType = (type, index) => {
  const val = [...value.value]
  const target = val[index] || {}
  val.splice(index, 1, { ...target, type })
  emit('update:model-value', JSON.stringify(val))
}

const onChangeNo = (no, index) => {
  const val = [...value.value]
  const target = val[index] || {}
  val.splice(index, 1, { ...target, no })
  emit('update:model-value', JSON.stringify(val))
}

const onRemove = index => {
  const val = [...value.value]
  val.splice(index, 1)
  emit('update:model-value', JSON.stringify(val))
}
</script>

<style scoped lang="scss">
.contact-json {
  width: 100%;
  &-row {
    display: flex;
    align-items: center;
    & + & {
      margin-top: 8px;
    }
  }
  &-type {
    width: 128px;
  }
  &-no {
    flex-grow: 1;
    margin: 0 10px;
  }
}
</style>
